/**
 * The script.js with codes JavaScript and libraries jQuery
 * 
 * @author Cesar Augustus Silva <cesaraugustussilva@linuxmail.org>
 * @copyright Copyright (c) 2013, Cesar Augustus Silva
 * @license http://www.gnu.org/licenses/gpl.html GNU GPL v3.0
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <­http://www.gnu.org/licenses/>.
 */

/*var _gaq = _gaq || [];
 _gaq.push(['_setAccount', 'UA-41597985-1']);
 _gaq.push(['_setDomainName', 'goiautos.com.br']);
 _gaq.push(['_trackPageview']);
 
 (function() {
 var ga = document.createElement('script');
 ga.type = 'text/javascript';
 ga.async = true;
 ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
 var s = document.getElementsByTagName('script')[0];
 s.parentNode.insertBefore(ga, s);
 })();*/

jQuery.noConflict()(function($) {
    var alarmTimeout;

    var maskmoneyDefault = {
        allowNegative: false,
        decimal: ',',
        symbol: 'R$ ',
        symbolStay: true,
        thousands: '.'
    };

    function alarm(type, text, title, timeout) {
        if (!$("#alarm").length) {
            var elalarm, elicon, eltext, eltitle;
            elalarm = $(document.createElement("div")).attr("id", "alarm");
            eldiv = $(document.createElement("div"));
            elicon = $(document.createElement("span")).addClass("icon");
            eltext = $(document.createElement("span")).addClass("text");
            eltitle = $(document.createElement("span")).addClass("title");
            eldiv.append(elicon, eltitle, eltext);
            elalarm.append(eldiv);
            $("body").append(elalarm);
        }
        else {
            clearTimeout(alarmTimeout);
            $("#alarm").removeClass();
        }
        if (title != undefined)
            $("#alarm span.title").html(title);
        else if (type == "error")
            $("#alarm span.title").html("Erro!");
        else if (type == "success")
            $("#alarm span.title").html("Sucesso!");
        else if (type == "warning")
            $("#alarm span.title").html("Atenção!");
        $("#alarm span.text").html(text);
        $("#alarm").addClass(type).slideDown(500);
        if (timeout == undefined)
            timeout = 3500;
        alarmTimeout = setTimeout(function() {
            $("#alarm").slideUp(500, function() {
                $("#alarm").remove()
            });
        }, timeout);
    }

    $(document).ready(function() {
        placeholder();
    });

    if ($("form").length) {
        $("form :input.required").focusout(function() {
            var value = $(this).val().replace(/[\s\-()/.]/g, "");
            if ($(this).hasClass("empty") && value != "")
                $(this).removeClass("empty").addClass("modified");
            if ($(this).hasClass("modified") && value == "")
                $(this).removeClass("modified").addClass("empty");
        });
        $("form").submit(function() {
            $(this).find(":input.required").each(function() {
                if ($(this).val().replace(/[\s\-()/.]/g, "") == "")
                    $(this).addClass("empty");
                else
                    $(this).removeClass("empty");
            });
            if ($(this).find(".empty").length) {
                var title = $(this).find(".empty").attr("title");
                alarm("warning", "Preencha o campo <strong>" + title + "</strong> corretamente.");
                $(this).find(".empty")[0].focus();
            }
        });
    }

    if ($("#header .top-line").length) {
        $(".top-line ul.contact li.login").click(function() {
            if ($("ul.contact form#login").is(":visible"))
                $("ul.contact form#login").slideUp();
            else
                $("ul.contact form#login").slideDown(function() {
                    $(this).find(":input:first").focus();
                });
        });
        if ($("ul.contact form#login :input").click(function() {
            $(this).focus();
        }))
            ;
        if ($("ul.contact form#login").focusout(function() {
            if ($("ul.contact form#login").is(":visible")) {
                setTimeout(function() {
                    if ($("ul.contact form#login :input:focus").length == 0)
                        $("ul.contact form#login").slideUp();
                }, 500);
            }
        }))
            ;
        $("form#login").submit(function() {
            if (!$(this).find(".empty").length) {
                var data = $(this).serialize();
                $.ajax({
                    type: "post",
                    url: "<?= _ACT_URI_ ?>login.php",
                    data: data,
                    success: function(msg) {
                        if (msg == "SUCCESS")
                            window.location.href = "<?= __BASE_URI__ ?>painel";
                        else if (msg == "INVALID")
                            alarm("error", "E-mail ou senha inválidos.", "Acesso Negado!");
                        else if (msg == "INACTIVE") {
                            $("form#login-access")
                                    .attr("action", "<?= __BASE_URI__ ?>cadastro")
                                    .attr("method", "post");
                        }
                        else
                            alarm("warning", msg);
                    }
                });
            }
            return false;
        });
    }

    if ($(".widget.search-detailed").length) {
        $(".search-detailed .tabs a").click(function() {
            var index = $(".search-detailed .tabs a").index(this);
            $(".search-detailed .tabs a").removeClass("current");
            $(".search-detailed .panes form").fadeOut(400);
            $(".search-detailed .panes form").eq(index).fadeIn(600);
            $(this).addClass("current");
            return false;
        });
        $("form#search-vehicles select").change(function() {
            if (/^(type|brand)$/g.test($(this).attr("name"))) {
                var selnext = $(this).next().next().attr("name");
                $("form#search-vehicles select[name='" + selnext + "']")
                        .addClass("disabled")
                        .attr("disabled", true)
                        .html("<option></option>");
                if ($(this).val() != "") {
                    var id_type = $("form#search-vehicles select[name='type']").val();
                    var id_brand = $("form#search-vehicles select[name='brand']").val();
                    $("form#search-vehicles select[name='" + selnext + "'] option:eq(0)").html("Carregando...");
                    $.ajax({
                        url: "<?= _AJX_URI_ ?>search-vehicles.php",
                        dataType: "json",
                        data: {
                            id_type: id_type,
                            id_brand: id_brand,
                            search: $(this).attr("name")
                        },
                        success: function(j) {
                            var options = "<option></option>";
                            if (j.length > 0) {
                                for (var i = 0; i < j.length; i++) {
                                    if (i > 0) {
                                        if (j[i].detached == 0 && j[i - 1].detached == 1)
                                            options += "<option disabled value=\"\"> - </option>";
                                    }
                                    options += "<option value=\"" + j[i].id + "\">" + j[i].name + "</option>";
                                }
                                $("form#search-vehicles select[name='" + selnext + "']")
                                        .attr("disabled", false)
                                        .html(options)
                                        .removeClass("disabled");
                            }
                            else
                                $("form#search-vehicles select[name='" + selnext + "'] option:eq(0)").html("");
                            $("form#search-vehicles select[name='" + selnext + "']").change();
                        }
                    });
                }
                else
                    $("form#search-vehicles select[name='" + selnext + "']").change();
            }
        });
        $("form#search-vehicles").submit(function() {
            if ($("form#search-vehicles select[name='type']").val() == "") {
                alarm("warning", "Selecione o <strong>tipo</strong> de veículo.");
                return false;
            }
            else {
                $("form#search-vehicles")
                        .attr("action", "<?= _ACT_URI_ ?>search-result.php")
                        .attr("method", "post");
            }
        });
        $("form#search-resales select[name='city-resale']").change(function() {
            $("form#search-resales select[name='enterprise-resale']")
                    .addClass("disabled")
                    .attr("disabled", true)
                    .html("<option></option>");
            if ($(this).val() != "") {
                var id_city = $(this).val();
                $("form#search-resales select[name='enterprise-resale'] option:eq(0)").html("Carregando...");
                $.ajax({
                    url: "<?= _AJX_URI_ ?>search-resales.php",
                    dataType: "json",
                    data: {
                        id_city: id_city,
                        search: "city"
                    },
                    success: function(j) {
                        var options = "<option></option>";
                        if (j.length > 0) {
                            for (var i = 0; i < j.length; i++)
                                options += "<option value=\"" + j[i].id + "\">" + j[i].fancyname + "</option>";
                            $("form#search-resales select[name='enterprise-resale']")
                                    .attr("disabled", false)
                                    .html(options)
                                    .removeClass("disabled");
                        }
                        else
                            $("form#search-resales select[name='enterprise-resale'] option:eq(0)").html("");
                    }
                });
            }
        });
        $("form#search-resales select[name='enterprise-resale']").change(function() {
            if ($(this).val() != "") {
                var fancyname = $("form#search-resales select[name='enterprise-resale'] option:selected").text()
                fancyname = encodeURIComponent(fancyname).replace(/%20/g, "-").toLowerCase();
                window.location.href = "<?= __BASE_URI__ ?>revenda/" + fancyname + "/" + $(this).val();
            }
        });
        $("form#search-resales select[name='state-private']").change(function() {
            $("form#search-resales select[name='city-private']")
                    .addClass("disabled")
                    .attr("disabled", true)
                    .html("<option></option>");
            if ($(this).val() != "") {
                var id_state = $(this).val();
                $("form#search-resales select[name='city-private'] option:eq(0)").html("Carregando...");
                $.ajax({
                    url: "<?= _AJX_URI_ ?>search-resales.php",
                    dataType: "json",
                    data: {
                        id_state: id_state,
                        search: "state"
                    },
                    success: function(j) {
                        var options = "<option></option>";
                        if (j.length > 0) {
                            for (var i = 0; i < j.length; i++)
                                options += "<option value=\"" + j[i].id + "\">" + j[i].name + "</option>";
                            $("form#search-resales select[name='city-private']")
                                    .attr("disabled", false)
                                    .html(options)
                                    .removeClass("disabled");
                        }
                        else
                            $("form#search-resales select[name='city-private'] option:eq(0)").html("");
                    }
                });
            }
        });
        $("form#search-resales select[name='city-private']").change(function() {
            if ($(this).val() != "") {
                var city = $("form#search-resales select[name='city-private'] option:selected").text()
                city = encodeURIComponent(city).replace(/%20/g, "-").toLowerCase();
                window.location.href = "<?= __BASE_URI__ ?>pesquisa/anunciante.particular/cidade." + city;
            }
        });
    }

    if ($(".widget.access-control").length) {
        $("form#search-live").submit(function() {
            $("form#search-live")
                    .attr("action", "<?= _ACT_URI_ ?>search-result.php")
                    .attr("method", "post");
        });
    }

    if ($(".widget.new-search").length) {
        $(".new-search a").click(function() {
            if ($("#wrapper > .header").css("display") == "none")
                $("#wrapper > .header").slideDown(1000);
            else
                $("#wrapper > .header").slideUp(1000);
        });
    }

    if ($("#wrapper .content.home").length) {
        $("#codaslider").codaSlider({
            autoHeight: false,
            autoSlide: true,
            autoSlideInterval: 5000,
            dynamicArrows: false,
            slideEaseDuration: 300,
            slideEaseFunction: "easeInQuad"
        });
    }

    if ($("#wrapper .content.contact").length) {
        $("input[name='phone']").bind({
            focus: function() {
                $(this).mask("(99) 9999-9999?9", {placeholder: " "});
            },
            focusout: function() {
                var number, mask;
                $(this).unmask();
                number = $(this).val().replace(/\D/g, "");
                if (number.length > 10)
                    mask = "(99) 99999-999?9";
                else
                    mask = "(99) 9999-9999?9";
                $(this).mask(mask, {placeholder: " "});
            }
        });
        $("form#contact select[name='state']").change(function() {
            $("form#contact select[name='city']")
                    .addClass("disabled")
                    .attr("disabled", true)
                    .html("<option></option>");
            if ($(this).val() != "") {
                var state = $(this).val();
                $("form#contact select[name='city'] option:eq(0)").html("Carregando...");
                $.ajax({
                    url: "<?= _AJX_URI_ ?>contact.php",
                    dataType: "json",
                    data: {state: state},
                    success: function(j) {
                        var options = "<option></option>";
                        if (j.length > 0) {
                            for (i = 0; i < j.length; i++)
                                options += "<option>" + j[i].name + "</option>";
                            $("form#contact select[name='city']")
                                    .attr("disabled", false)
                                    .html(options)
                                    .removeClass("disabled");
                        }
                        else
                            $("form#contact select[name='city'] option:eq(0)").html("");
                    }
                });
            }
        });
        $("form#contact").submit(function() {
            if (!$(this).find(".empty").length) {
                var data = $(this).serialize();
                $.ajax({
                    type: "post",
                    url: "<?= _ACT_URI_ ?>contact.php",
                    data: data,
                    success: function(msg) {
                        if (msg.substr(-2) == "OK") {
                            alarm("success", "Sua mensagem foi enviada com sucesso.");
                            $("#contact")[0].reset();
                        }
                        else if (msg.substr(-5) == "ERROR")
                            alarm("error", "Por favor, tente novamente mais tarde.");
                        else
                            alarm("warning", msg);
                    }
                });
            }
            return false;
        });
    }

    if ($("#wrapper .content.login").length) {
        $("input[name='cpfcnpj']").bind({
            focusin: function() {
                $(this).unmask();
            },
            focus: function() {
                var number;
                number = $(this).val().replace(/\D/g, "");
                $(this).val(number);
                $(this).mask("99999999999?999", {placeholder: ""});
            },
            focusout: function() {
                var number;
                $(this).unmask();
                number = $(this).val().replace(/\D/g, "");
                $(this).val(number);
                if (number.length == 14)
                    $(this).mask("99.999.999/9999-99");
                else if (number.length == 11)
                    $(this).mask("999.999.999-99");
                else
                    $(this).val("");
            }
        });
        $("form#login-access").submit(function() {
            var rtn = false;
            if (!$(this).find(".empty").length) {
                var data = $(this).serialize();
                $.ajax({
                    type: "post",
                    url: "<?= _ACT_URI_ ?>login.php",
                    async: false,
                    data: data,
                    success: function(msg) {
                        if (msg == "SUCCESS")
                            window.location.href = "<?= __BASE_URI__ ?>painel";
                        else if (msg == "INVALID")
                            alarm("error", "E-mail ou senha inválidos.", "Acesso Negado!");
                        else if (msg == "INACTIVE") {
                            $("form#login-access")
                                    .attr("action", "<?= __BASE_URI__ ?>cadastro")
                                    .attr("method", "post");
                            rtn = true;
                        }
                        else
                            alarm("warning", msg);

                    }
                });
            }
            return rtn;
        });
        $("form#login-register").submit(function() {
            var rtn = false;
            if (!$(this).find(".empty").length) {
                var data = $(this).serialize();
                $.ajax({
                    type: "post",
                    url: "<?= _ACT_URI_ ?>login.php",
                    async: false,
                    data: data,
                    success: function(msg) {
                        if (msg == "EMAIL_EXISTS")
                            alarm("warning", "Este <strong>E-mail</strong> já está cadastrado.");
                        else if (msg == "CPFCNPJ_EXISTS")
                            alarm("warning", "Este <strong>CPF/CNPJ</strong> já está cadastrado.");
                        else if (msg == "SUCCESS") {
                            $("form#login-register")
                                    .attr("action", "<?= __BASE_URI__ ?>cadastro")
                                    .attr("method", "post");
                            rtn = true;
                        }
                        else
                            alarm("warning", msg);
                    }
                });
            }
            return rtn;
        });
    }

    if ($("#wrapper .content.vehicle").length) {
        $("input[name='phone']").bind({
            focus: function() {
                $(this).mask("(99) 9999-9999?9", {placeholder: " "});
            },
            focusout: function() {
                var number, mask;
                $(this).unmask();
                number = $(this).val().replace(/\D/g, "");
                if (number.length > 10)
                    mask = "(99) 99999-999?9";
                else
                    mask = "(99) 9999-9999?9";
                $(this).mask(mask, {placeholder: " "});
            }
        });
        $(".content.vehicle .photos ul").PikaChoose({
            autoPlay: false,
            carousel: true
        });
        $(".content.vehicle .details button").click(function() {
            $(".proposal, .proposal-layer-transparent").fadeIn("fast");
        });
        $("form#proposal").submit(function() {
            if (!$(this).find(".empty").length) {
                var data = $(this).serialize();
                $.ajax({
                    type: "post",
                    url: "<?= _ACT_URI_ ?>proposal.php",
                    data: data,
                    success: function(msg) {
                        if (msg == 'OK') {
                            $("form#proposal")[0].reset();
                            alarm("success", "A proposta acabou de ser enviada.");
                        }
                        else if (msg == 'ERROR')
                            alarm("error", "Estamos com problemas técnicos, por favor tente novamente mais tarde.");
                        else
                            alarm("warning", msg);
                    }
                });
            }
            return false;
        });
    }

    if ($("#wrapper .content.search-products").length) {
        $("form#search-products").submit(function() {
            if (!$(this).find(".empty").length) {
                $("form#search-products")
                        .attr("action", "<?= _ACT_URI_ ?>search-products.php")
                        .attr("method", "post");
            }
            else
                return false;
        });
    }

    if ($("#wrapper .content.cpanel").length) {
        /*
         $(window).scroll(function() {
         if ($(".content.cpanel").height() > $(".sidebar.left").height()) {
         topBottom = $(".content.cpanel").height() - $(".sidebar.left").height();
         pointTop = $(".content.cpanel").position().top - 10;
         pointBottom = pointTop + topBottom;
         if ($(this).scrollTop() > pointBottom)
         $(".sidebar.left").css({ position: "relative", top: topBottom+"px" });
         else if ($(this).scrollTop() > pointTop)
         $(".sidebar.left").css({ position: "fixed", top: "10px" });
         else
         $(".sidebar.left").css({ position: "", top: "" });
         }
         });
         */
    }

    if ($("#wrapper .content.register").length) {
        $("form#register").submit(function() {
            if (!$(this).find(".empty").length) {
                if ($(this).find("input[name='password']").val() != $(this).find("input[name='password-repeated']").val()) {
                    alarm("warning", "Os campos <strong>Senha</strong> e <strong>Repetir senha</strong> devem ser iguais.");
                    return false;
                }
                var data = $(this).serialize();
                $.ajax({
                    type: "post",
                    url: "<?= _ACT_URI_ ?>register.php",
                    data: data,
                    success: function(msg) {
                        if (msg == 'OK') {
                            $("form#register").css({display: "none"});
                            $(".content.register .success").css({display: "block"});
                            $(".content.register .banners-resellers").css({height: "425px"});
                            $("html,body").animate({scrollTop: 0}, 0);
                        }
                        else
                            alarm("error", "Estamos com problemas técnicos, por favor tente novamente mais tarde.");
                    }
                });
            }
            return false;
        });
        $("form#confirmation").submit(function() {
            var data = $(this).serialize();
            $.ajax({
                type: "post",
                url: "<?= _ACT_URI_ ?>register.php",
                data: data,
                success: function(msg) {
                    if (msg == 'OK')
                        alarm("success", "O e-mail de confirmação acabou de ser enviado.");
                    else
                        alarm("error", "Estamos com problemas técnicos, por favor tente novamente mais tarde.");
                }
            });
            return false;
        });
    }

    if ($(".widget.cpanel-menus").length) {
        $(".widget.cpanel-menus ul li.news").each(function() {
            var n = 0;
            var li = $(this);
            setInterval(function() {
                if (n == 0) {
                    li.find("a").css({color: "#FF4E00"});
                    n = 1;
                }
                else {
                    li.find("a").css({color: ""});
                    n = 0;
                }
            }, 500);
        });
        $(".widget.cpanel-menus li a.createad").click(function() {
            if ($("div.exceededad").length) {
                alarm("warning", "O limite de cadastro de anúncios foi atingido.", "Limite atingido!");
                return false;
            }
        });
    }

    if ($(".cppage.ads").length) {
        /*code here*/
        $('.remove-ads.product').click(function() {
            id_product = $(this).attr('rel');
            if (confirm("Deseja realmente excluir esse produto?")) {
                $.ajax({
                    type: "post",
                    url: "<?= _ACT_URI_ ?>products.php",
                    data: {page: 'removead', id: id_product},
                    success: function(msg) {
                        if (msg = 'OK') {
                            location.reload();
                        } else if (msg = 'ERRO') {
                            alarm("warning", "Ocorreu um problema ao excluir o produto", "Erro!");
                        }

                    }
                });
            } else {
                return false;
            }
        });
    }

    if ($(".cppage.register").length) {
        $("input[name='cpfcnpj']").each(function() {
            var number;
            number = $(this).val().replace(/\D/g, "");
            $(this).val(number);
            if (number.length == 14)
                $(this).mask("99.999.999/9999-99");
            else if (number.length == 11)
                $(this).mask("999.999.999-99");
            else
                $(this).val("");
        });
        $("form#register .phones .del").click(function() {
            var phone_id = $(this).parents(".phones li").find("input[name^='phone-id']").val();
            if (phone_id != 0) {
                excluded = $("form#register input[name='phones-excluded']");
                if (excluded.val() == "")
                    excluded.val(phone_id);
                else
                    excluded.val(excluded.val() + "," + phone_id);
            }
        });
        $("form#register").submit(function() {
            if (!$(this).find(".empty").length) {
                var data = $(this).serialize();
                $.ajax({
                    type: "post",
                    url: "<?= _ACT_URI_ ?>cpanel.php",
                    data: data,
                    success: function(msg) {
                        if (msg == 'ERROR')
                            alarm("error", "Estamos com problemas técnicos, por favor tente novamente mais tarde.");
                        else
                            alarm("success", "Seus dados foram atualizados.");
                    }
                });
            }
            return false;
        });
    }

    if ($("#wrapper .content.register, .cppage.register").length) {
        $("input[name='cpf']").mask("999.999.999-99");
        $("input[name='cnpj']").mask("99.999.999/9999-99");
        $("input[name='cep']").mask("99.999-999", {placeholder: " "});
        $("input[name='number']").mask("9?999", {placeholder: ""});
        $("form#register .phones li input[name^='phone-areacode']").mask("99", {placeholder: ""});
        $("form#register .phones li input[name^='phone-number']").mask("9999-9999?9", {placeholder: " "});
        $("form#register .phones li input[name^='phone-number']").bind({
            focus: function() {
                $(this).mask("9999-9999?9", {placeholder: " "});
            },
            focusout: function() {
                var number, mask;
                $(this).unmask();
                number = $(this).val().replace(/\D/g, "");
                if (number.length > 8)
                    mask = "99999-999?9";
                else
                    mask = "9999-9999?9";
                $(this).mask(mask, {placeholder: " "});
            }
        });
        $("form#register select[name='state']").change(function() {
            $("form#register select[name='city']")
                    .addClass("disabled")
                    .attr("disabled", true)
                    .html("<option></option>");
            if ($(this).val() != "") {
                var state = $(this).val();
                $("form#register select[name='city'] option:eq(0)").html("Carregando...");
                $.ajax({
                    url: "<?= _AJX_URI_ ?>register.php",
                    dataType: "json",
                    data: {state: state},
                    success: function(j) {
                        var options = "<option></option>";
                        if (j.length > 0) {
                            for (i = 0; i < j.length; i++)
                                options += "<option value=\"" + j[i].id + "\">" + j[i].name + "</option>";
                            $("form#register select[name='city']")
                                    .attr("disabled", false)
                                    .html(options)
                                    .removeClass("disabled");
                        }
                        else
                            $("form#register select[name='city'] option:eq(0)").html("");
                    }
                });
            }
        });
        $("form#register .phones .add").click(function() {
            var first_phone = $("form#register .phones li:first-child");

            first_phone.find("input").each(function() {
                if ($(this).val().replace(/\D/g, "") == "")
                    $(this).addClass("empty");
                else
                    $(this).removeClass("empty");
            });

            if (first_phone.find(".empty").length) {
                var title = first_phone.find(".empty").attr("title");
                alarm("warning", "Preencha o campo <strong>" + title + "</strong> corretamente.");
                first_phone.find(".empty")[0].focus();
                return false;
            }

            var stop = false;
            $("form#register .phones li").each(function() {
                if ($(this).is(":not(:first-child)")) {
                    var areacode = $(this).find("input[name^='phone-areacode']").val();
                    var number = $(this).find("input[name^='phone-number']").val();
                    if (areacode == first_phone.find("input[name^='phone-areacode']").val())
                        if (number == first_phone.find("input[name^='phone-number']").val()) {
                            alarm("warning", "Esse <strong>Telefone</strong> já está adicionado.");
                            stop = true;
                        }
                }
            });
            if (stop)
                return false;

            var type = first_phone.find("select option:selected").val();
            first_phone.find("select option").removeAttr("selected");
            first_phone.find("input[name^='phone-areacode']").unmask();
            first_phone.find("input[name^='phone-number']").unmask();

            var clone = first_phone.clone(true);
            clone.find("select option[value='" + type + "']").attr("selected", true);
            clone.find("select").val(clone.find("select option:selected").val());
            clone.find("input").addClass("required");
            clone.find("input[name^='phone-areacode']").mask("99", {placeholder: ""});
            clone.find("input[name^='phone-number']").bind({
                focus: function() {
                    $(this).mask("9999-9999?9", {placeholder: " "});
                },
                focusout: function() {
                    var number, mask;
                    $(this).unmask();
                    number = $(this).val().replace(/\D/g, "");
                    if (number.length > 8)
                        mask = "99999-999?9";
                    else
                        mask = "9999-9999?9";
                    $(this).mask(mask, {placeholder: " "});
                }
            });
            first_phone.after(clone.fadeIn("slow"));

            first_phone.find("input[name^='phone-areacode']").mask("99", {placeholder: ""});
            first_phone.find("input[name^='phone-number']").bind({
                focus: function() {
                    $(this).mask("9999-9999?9", {placeholder: " "});
                },
                focusout: function() {
                    var number, mask;
                    $(this).unmask();
                    number = $(this).val().replace(/\D/g, "");
                    if (number.length > 8)
                        mask = "99999-999?9";
                    else
                        mask = "9999-9999?9";
                    $(this).mask(mask, {placeholder: " "});
                }
            });
            first_phone.find("select").val(first_phone.find("select option:first-child").val());
            first_phone.find("input").removeClass("required modified").val("");
            first_phone.find("input[name^='phone-id']").val(0);

            first_phone.find("select").focus();

            return false;
        });
        $("form#register .phones .del").click(function() {
            $(this).parents(".phones li").fadeOut("fast", function() {
                $(this).remove();
                if ($("form#register .phones li").length == 1)
                    $("form#register .phones li input").addClass("required");
            });
            return false;
        });
        $("form#register .phones li:first-child :input").bind({
            keydown: function(e) {
                if (e.which == 13) {
                    $(this).trigger("focusout");
                    $("form#register .phones li:first-child .add").trigger("click");
                    return false;
                }
            },
            focusout: function() {
                var value = $(this).val().replace(/\D/g, "");
                if ($(this).hasClass("empty") && value != "")
                    $(this).removeClass("empty").addClass("modified");
                if ($(this).hasClass("modified") && value == "")
                    $(this).removeClass("modified").addClass("empty");
            }
        });
    }

    if ($(".cppage.chpasswd").length) {
        $("form#chpasswd").submit(function() {
            if (!$(this).find(".empty").length) {
                if ($(this).find("input[name='current-password']").val() == $(this).find("input[name='new-password']").val()) {
                    alarm("warning", "Os campos <strong>Senha atual</strong> e <strong>Nova senha</strong> devem ser diferentes.");
                    return false;
                }
                if ($(this).find("input[name='new-password']").val() != $(this).find("input[name='password-repeated']").val()) {
                    alarm("warning", "Os campos <strong>Nova senha</strong> e <strong>Repetir senha</strong> devem ser iguais.");
                    return false;
                }
                var data = $(this).serialize();
                $.ajax({
                    type: "post",
                    url: "<?= _ACT_URI_ ?>cpanel.php",
                    data: data,
                    success: function(msg) {
                        if (msg == 'INVALID')
                            alarm("warning", "Senha atual incorreta.");
                        else if (msg == 'ERROR')
                            alarm("error", "Estamos com problemas técnicos, por favor tente novamente mais tarde.");
                        else {
                            alarm("success", "A sua senha foi alterada.");
                            $("form#chpasswd")[0].reset();
                        }
                    }
                });
            }
            return false;
        });
    }

    if ($(".cppage.createad").length) {
        $("ul.pictures p a").colorbox({
            fixed: true,
            iframe: true,
            innerWidth: 700,
            innerHeight: 480,
            href: "<?= __BASE_URI__ ?>tips-photos?iframe=1"
        });
        $("input[name='renavam']").mask("999999999?99", {placeholder: ""});
        $("input[name='parcelsquantity']").mask("9?999", {placeholder: ""});
        $("input[name='price']").maskMoney(maskmoneyDefault);
        $("input[name='discount']").maskMoney(maskmoneyDefault);
        $("input[name='inputvalue']").maskMoney(maskmoneyDefault);
        $("input[name='parcelvalue']").maskMoney(maskmoneyDefault);
        $("input[name='plate']").mask("aaa-9999", {placeholder: " "});
        $("input[name='km']").mask("9?99999999", {placeholder: ""});
        $("input[name='renavam']").focusout(function() {
            $(this).val($(this).val().replace(/\D/g, ""));
        });
        $("input[name='cpfcnpj_owner']").bind({
            focusin: function() {
                $(this).unmask();
            },
            focus: function() {
                var number;
                number = $(this).val().replace(/\D/g, "");
                $(this).val(number);
                $(this).mask("99999999999?999", {placeholder: ""});
            },
            focusout: function() {
                var number;
                $(this).unmask();
                number = $(this).val().replace(/\D/g, "");
                $(this).val(number);
                if (number.length == 14)
                    $(this).mask("99.999.999/9999-99");
                else if (number.length == 11)
                    $(this).mask("999.999.999-99");
                else
                    $(this).val("");
            }
        });
        $("input[name='cpfcnpj_owner']").trigger("focusout");
        $("input[name='price'],input[name='discount']").keyup(function() {
            var price, discount, t, i, d, s, j;
            price = $("input[name='price']").val().replace(/\D/g, "");
            discount = $("input[name='discount']").val().replace(/\D/g, "");
            if (price == 0 && discount == 0)
                $("input[name='totalprice']").val("");
            else {
                t = price - discount;
                s = (t < 0) ? "- " : "";
                t = "" + ((t < 0) ? t * -1 : t);
                i = (t.length > 2) ? t.slice(0, -2) : "0";
                if (t.length < 2)
                    d = "0" + ((t.length == 1) ? t : "");
                else if (t.length > 2)
                    d = t.slice(-2);
                else
                    d = t;
                j = (j = i.length) > 3 ? j % 3 : 0;
                t = "R$ " + s + (j ? i.substr(0, j) + "." : "");
                t += i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + ".");
                t += "," + Math.abs("0." + d).toFixed(2).slice(-2);
                if (s == "- ")
                    $("input[name='totalprice']").addClass("negative");
                else
                    $("input[name='totalprice']").removeClass("negative");
                $("input[name='totalprice']").val(t);
            }
        });
        $("input[name='price'],input[name='discount']").trigger("focus");
        $("input[name='inputvalue']").trigger("focus");
        $("input[name='parcelvalue']").trigger("focus");
        $("select[name='plan']").focus();
        $("body").scrollTop(0);
        $("input[name='price'],input[name='discount']").trigger("keyup");
        $("form#createad input[name='funded']").change(function() {
            var inputs = $("form#createad .financing .input");
            if ($(this).val() == 1) {
                inputs.removeClass("disabled").addClass("required");
                inputs.attr("disabled", false);
            }
            else {
                inputs.removeClass("required").addClass("disabled");
                inputs.attr("disabled", true);
            }
        });
        $("form#createad select[name='plan']").change(function() {
            $("form#createad select[name='type']")
                    .addClass("disabled")
                    .attr("disabled", true)
                    .html("<option></option>");
            if ($(this).val() != "") {
                var id_plan = $(this).val();
                $("form#createad select[name='type'] option:eq(0)").html("Carregando...");
                $.ajax({
                    url: "<?= _AJX_URI_ ?>search-vehicles.php",
                    dataType: "json",
                    data: {
                        id_plan: id_plan,
                        search: $(this).attr("name")
                    },
                    success: function(j) {
                        var options = "<option></option>";
                        if (j.length > 0) {
                            for (i = 0; i < j.length; i++)
                                options += "<option value=\"" + j[i].id + "\">" + j[i].name + "</option>";
                            $("form#createad select[name='type']")
                                    .attr("disabled", false)
                                    .html(options)
                                    .removeClass("disabled");
                        }
                        else
                            $("form#createad select[name='type'] option:eq(0)").html("");
                        $("form#createad select[name='type']").change();
                    }
                });
            }
            else
                $("form#createad select[name='type']").change();
        });
        $("form#createad select").change(function() {
            if (/^(type|brand|model)$/g.test($(this).attr("name"))) {
                var selnext = $(this).parents(":eq(0)").next().find("select").attr("name");
                $("form#createad select[name='" + selnext + "']")
                        .addClass("disabled")
                        .attr("disabled", true)
                        .html("<option></option>");
                if ($(this).val() != "") {
                    var id_type = $("form#createad select[name='type']").val();
                    var id_brand = $("form#createad select[name='brand']").val();
                    var id_model = $("form#createad select[name='model']").val();
                    $("form#createad select[name='" + selnext + "'] option:eq(0)").html("Carregando...");
                    $.ajax({
                        url: "<?= _AJX_URI_ ?>search-vehicles.php",
                        dataType: "json",
                        data: {
                            id_type: id_type,
                            id_brand: id_brand,
                            id_model: id_model,
                            search: $(this).attr("name")
                        },
                        success: function(j) {
                            var options = "<option></option>";
                            if (j.length > 0) {
                                for (i = 0; i < j.length; i++){
                                    options += "<option value=\"" + j[i].id + "\">" + j[i].name + "</option>";
                                }
                                $("form#createad select[name='" + selnext + "']")
                                        .attr("disabled", false)
                                        .html(options)
                                        .removeClass("disabled");
                            }
                            else
                                $("form#createad select[name='" + selnext + "'] option:eq(0)").html("");
                            $("form#createad select[name='" + selnext + "']").change();
                        }
                    });
                }
                else
                    $("form#createad select[name='" + selnext + "']").change();
            }
        });
        $("form#createad select[name='type']").change(function() {
            var id_type = $(this).val();
            $.ajax({
                url: "<?= _AJX_URI_ ?>details.php",
                dataType: "json",
                data: {id_type: id_type},
                success: function(j) {
                    var details = "";
                    if (j.length > 0) {
                        for (i = 0; i < j.length; i++) {
                            details += "<input type=\"checkbox\" name=\"details[]\" value=\"" + j[i].id + "\">";
                            details += "<span>" + j[i].name + "</span>";
                        }
                        $("form#createad div.details div.radio").html(details);
                        $("form#createad div.details").css({display: "block"});
                    }
                    else {
                        $("form#createad div.details").css({display: "none"});
                        $("form#createad div.details .radio").html("");
                    }
                }
            });
        });
        $("form#createad select[name='model'], form#createad select[name='firstreg'], form#createad select[name='modelyear']").change(function() {
            var id_model = $("form#createad select[name='model']").val();
            var firstreg = $("form#createad select[name='firstreg']").val();
            var modelyear = $("form#createad select[name='modelyear']").val();
            if (id_model != "") {
                $.ajax({
                    url: "<?= _AJX_URI_ ?>prices-average.php",
                    dataType: "json",
                    data: {
                        id_model: id_model,
                        firstreg: firstreg,
                        modelyear: modelyear
                    },
                    success: function(j) {
                        $("form#createad div.price-analysis p.media .value").html("R$ " + j.average);
                        $("form#createad div.price-analysis p.more .value").html("R$ " + j.more);
                        $("form#createad div.price-analysis p.less .value").html("R$ " + j.less);
                        $("form#createad div.price-analysis h3").html("Média de valores");
                        $("form#createad div.price-analysis p.small").css({display: "block"});
                        $("form#createad div.price-analysis p.large").css({display: "none"});
                        $("form#createad div.price-analysis p.price").css({display: "block"});
                    }
                });
            }
            else {
                $("form#createad div.price-analysis h3").html("Análise de preço");
                $("form#createad div.price-analysis p.small").css({display: "none"});
                $("form#createad div.price-analysis p.large").css({display: "block"});
                $("form#createad div.price-analysis p.price").css({display: "none"});
            }
        });
        $("form#createad select[name='modelyear']").trigger("change");
        $("form#createad input[name^='pictures']").change(function(e) {
            var message = "";
            var timeout = undefined;
            var fileExt = $(this).val().substr($(this).val().lastIndexOf(".") + 1);
            //var fileSize = this.files[0].size;
            var extensions = ["gif", "jpg", "jpeg", "png"];
            if ($.inArray(fileExt.toLowerCase(), extensions) == -1)
                message = "O tipo de arquivo selecionado não é permitido.";
            /*else if (fileSize > 1500000) {
             message = "O tamanho da imagem ultrapassa o limite permitido. (Máximo: 1,5MB)";
             timeout = 5000;
             }*/
            if (message != "") {
                alarm("warning", message, undefined, timeout);
                $(this).val("");
            }
        });
        $("form#createad .pictures .del").click(function() {
            var id, excluded, li;
            id = $(this).attr("data");
            excluded = $("form#createad input[name='pictures-excluded']");
            if (excluded.val() == "")
                excluded.val(id);
            else
                excluded.val(excluded.val() + "," + id);
            li = $(this).parents(".pictures li");
            li.find("img").attr("src", li.find("img").attr("data-original"));
            li.find("input").attr("disabled", false);
            li.find("a.del").remove();
        });
        $("form#createad").submit(function() {
            var rtn = false;
            if (!$(this).find(".empty").length) {
                var pictures = false;
                $(this).find("input[name^='pictures[']").each(function() {
                    if ($(this).val() != "" || $(this).is(":disabled"))
                        pictures = true;
                });
                if (!pictures)
                    alarm("warning", "Adicione no mínimo uma <b>Foto do Veículo</b>.");
                else if ($("form#createad input[name='terms_accepted']").is(":not(:checked)"))
                    alarm("warning", "Deve aceitar os termos do contrato.");
                else {
                    var data = $(this).serialize();
                    $.ajax({
                        type: "post",
                        url: "<?= _AJX_URI_ ?>cpanel.php",
                        async: false,
                        data: data,
                        success: function(msg) {
                            if (msg == "SUCCESS") {
                                $("form#createad")
                                        .attr("action", "<?= _ACT_URI_ ?>cpanel.php")
                                        .attr("enctype", "multipart/form-data")
                                        .attr("method", "post");
                                rtn = true;
                            }
                            else if (msg == "RENAVAM_EXISTS") {
                                $("form#createad input[name='renavam']").focus();
                                alarm("warning", "Este <strong>RENAVAM</strong> já está cadastrado.");
                            }
                            else {
                                $("form#createad input[name='cpfcnpj_owner']").focus();
                                alarm("warning", msg);
                            }
                        }
                    });
                }
            }
            return rtn;
        });
    }

    if ($(".cppage.removead").length) {
        $("input.back").click(function() {
            window.location.href = "<?= __BASE_URI__ ?>painel";
        });
        $("form#removead").submit(function() {
            $("form#removead")
                    .attr("action", "<?= _ACT_URI_ ?>cpanel.php")
                    .attr("method", "post");
        });
    }

    if ($(".cppage.pictures").length) {
        $("form#pictures input[name^='file']").change(function(e) {
            var message = "";
            var timeout = undefined;
            var fileExt = $(this).val().substr($(this).val().lastIndexOf(".") + 1);
            var extensions = ["gif", "jpg", "jpeg", "png"];
            if ($.inArray(fileExt.toLowerCase(), extensions) == -1)
                message = "O tipo de arquivo selecionado não é permitido.";
            if (message != "") {
                alarm("warning", message, undefined, timeout);
                $(this).val("");
            }
        });
        $("form#pictures div .del").click(function() {
            var id, excluded, div;
            id = $(this).attr("data");
            if ($(this).hasClass("filepicture"))
                excluded = $("form#pictures input[name='filepicture-excluded']");
            else
                excluded = $("form#pictures input[name='filebrand-excluded']");
            excluded.val(id);
            div = $(this).parents("form#pictures div");
            div.find("img").attr("src", div.find("img").attr("data-original"));
            div.find("input").attr("disabled", false);
            div.find("a.del").remove();
        });
        $("form#pictures").submit(function() {
            $("form#pictures")
                    .attr("action", "<?= _ACT_URI_ ?>cpanel.php")
                    .attr("enctype", "multipart/form-data")
                    .attr("method", "post");
        });
    }

    if ($(".cppage.proposals").length) {
        $(".cppage.proposals .table .tbody ul").click(function() {
            $(this).removeClass("new");
            var id = $(this).attr("data");
            var id_product2 = $(this).attr("id");
            $.ajax({
                url: "<?= _AJX_URI_ ?>proposal.php",
                dataType: "json",
                data: {id: id, id_product: id_product2},
                success: function(j) {
                    var message = "";
                    if (j != false) {
                        message += "<p><strong>Nome</strong>: " + j.client + "</p>";
                        message += "<p><strong>Telefone</strong>: " + j.phone + "</p>";
                        message += "<p><strong>E-mail</strong>: " + j.email + "</p>";
                        message += "<pre><strong>Mensagem</strong>:<br/>" + j.message + "</pre>";
                    }
                    $(".cppage.proposals .message").html(message);
                }
            });
        });
    }

    //=====================================================================//
    //==================   Comparativo de veiculo   =======================//
    //=====================================================================//
    if ($('.add-comparative').length) {
        var object;
        $('.add-comparative').bind({
            click: function() {
                object = $(this);
                $.ajax({
                    type: "post",
                    url: "<?= _AJX_URI_ ?>comparative.php",
                    data: {id_vehicle: object.attr('rel')},
                    success: function(j) {
                        if (j == 'add') {
                            object.addClass('checked');
                        } else if (j == 'remove') {
                            object.removeClass('checked');
                        }
                    }
                });
            }
        });
    }


    if ($('.content.comparative').length) {
        var widthTotal;
        var total = 0;
        var marginLeft = 0;
        var widthTable = parseInt($('.table-comparative').css('width')) + 1;
        var blockAnimation = false;
        var objectRemove;
        var ulVehicle = 171;
        var quantityVehicle;
        $('.remove-comparative').click(function() {
            if (blockAnimation == false) {
                ulVehicle = 171;
                blockAnimation = true;
                widthTotal = parseInt($('.slide-comparative').css('width'));
                objectRemove = $(this).parent().parent();
                if ($(this).parent().parent().next().length) {
                    objectMove = $(this).parent().parent().next();
                } else {
                    objectMove = $(this).parent().parent();
                }
                if (objectMove.index() == 1) {
                    ulVehicle = 0;
                }
                quantityVehicle = $('.slide-comparative ul.table-comparative').size();

                if (quantityVehicle > 2) {
                    objectRemove.fadeTo('slow', 0, function() {
                        objectRemove.animate({
                            'margin-left': ulVehicle - objectMove.position().left
                        }, 500, function() {
                            objectRemove.remove();
                            $('.slide-comparative').css('width', widthTotal - ulVehicle);
                            quantityVehicle = quantityVehicle - 1;
                            blockAnimation = false;
                            $.ajax({
                                type: "post",
                                url: "<?= _AJX_URI_ ?>comparative.php",
                                data: {id_vehicle: objectRemove.attr('rel')},
                                success: function(j) {
                                    if (j == 'add') {
                                        object.addClass('checked');
                                    } else if (j == 'remove') {
                                        object.removeClass('checked');
                                    }
                                }
                            });
                            if (quantityVehicle <= 4) {
                                $('.next').fadeOut('fast');
                                $('.previous').fadeOut('fast');
                            }
                        });
                    });
                }
            }
        });
        $('.previous').ready(function() {
            marginLeft = parseInt($('.slide-comparative').css('margin-left'));
            if (marginLeft == 0) {
                $('.previous').css('display', 'none');
            }
        });

        $('.next').bind({
            click: function() {
                widthTotal = parseInt($('.slide-comparative').css('width'));
                marginLeft = parseInt($('.slide-comparative').css('margin-left'));
                if (blockAnimation == false) {
                    blockAnimation = true;
                    if (((widthTable * 4) == total + widthTotal - ulVehicle)) {
                        $('.next').css('display', 'none');
                    }
                    if ((total <= 0) && ((widthTable * 4) < total + widthTotal)) {
                        total = marginLeft - widthTable;
                        $('.slide-comparative').animate({'margin-left': total + 'px'}, 500, function() {
                            marginLeft = parseInt($('.slide-comparative').css('margin-left'));
                            if (marginLeft < 0) {
                                $('.previous').css('display', 'block');
                            }
                            blockAnimation = false;
                        });
                    } else {
                        blockAnimation = false;
                    }
                }
            },
            mouseover: function() {
                $(this).addClass('active-right');
            },
            mouseout: function() {
                $(this).removeClass('active-right');
            }
        });
        $('.previous').bind({
            click: function() {
                if ((total + ulVehicle) == 0) {
                    $('.previous').css('display', 'none');
                    $('.next').css('display', 'block');
                }
                if (blockAnimation == false) {
                    blockAnimation = true;
                    marginLeft = parseInt($('.slide-comparative').css('margin-left'));
                    if (total < 0) {
                        total = marginLeft + widthTable;
                        $('.slide-comparative').animate({'margin-left': total + 'px'}, 500, function() {
                            marginLeft = parseInt($('.slide-comparative').css('margin-left'));

                            if (total < 0) {
                                $('.next').css('display', 'block');
                            }
                            blockAnimation = false;
                        });
                    } else {
                        blockAnimation = false;
                    }
                }
            },
            mouseover: function() {
                $(this).addClass('active-left');
            },
            mouseout: function() {
                $(this).removeClass('active-left');
            }
        });
    }
    if ($(".cppage.change-plan").length) {

        $("form#change-plan select#plan").change(function() {
            $.ajax({
                type: "post",
                url: "<?= _AJX_URI_ ?>plan.php",
                data: {plan:$(this).val()},
                success: function(msg) {
                    $('div.description').addClass('alert-msg2');
                    $('div.description').html(msg);
                }
            });
        });
        $("form#change-plan").submit(function() {
            if ($('#plan').val() == '') {
                alarm('warning', 'Selecione um plano antes de continuar.');
                $('#plan').focus();
                return false;
            }
            if (!$(this).find(".empty").length) {
                var data = $(this).serialize();
                $.ajax({
                    type: "post",
                    url: "<?= _ACT_URI_ ?>plan.php",
                    data: data,
                    success: function(msg) {
                        if (msg == 'OK') {
                            location.href = '<?= __BASE_URI__ ?>painel';
                        }
                    }
                });
            }
            return false;
        });
    }

    if ($(".cppage.product").length) {

        $("form#product .pictures .del").click(function() {
            var id, excluded, li;
            id = $(this).attr("data");
            excluded = $("form#product input[name='pictures-excluded']");
            if (excluded.val() == "")
                excluded.val(id);
            else
                excluded.val(excluded.val() + "," + id);
            li = $(this).parents(".pictures li");
            li.find("img").attr("src", li.find("img").attr("data-original"));
            li.find("input").attr("disabled", false);
            li.find("a.del").remove();
        });

        $("input[name='name']").focus();
        $("input[name='price']").maskMoney(maskmoneyDefault);
        $("form#product").submit(function() {
            var rtn = false;
            $(this).find(":input.required").each(function() {
                if ($(this).val().replace(/[\s\-()/.]/g, "") == "") {
                    $(this).addClass("empty");
                    rtn = false;
                } else {
                    $(this).removeClass("empty");
                }
            });
            if ($(this).find(".empty").length) {
                var title = $(this).find(".empty").attr("title");
                alarm("warning", "Preencha o campo <strong>" + title + "</strong> corretamente.");
                $(this).find(".empty")[0].focus();
            }

            if (!$(this).find(".empty").length) {
                var pictures = false;
                $(this).find("input[name^='pictures[']").each(function() {
                    if ($(this).val() != "" || $(this).is(":disabled"))
                        pictures = true;
                });
                if (!pictures) {
                    alarm("warning", "Adicione no mínimo uma <b>Foto do Produto</b>.");
                    rtn = false;
                } else {
                    var data = $(this).serialize();
                    $("form#product")
                            .attr("action", "<?= _ACT_URI_ ?>products.php")
                            .attr("enctype", "multipart/form-data")
                            .attr("method", "post");
                    rtn = true;
                }
            }
            return rtn;
        });
    }

    if ($('.cppage.financial').length) {
        $(".cppage.financial a.pay-ads, .cppage.financial a.pay-product").click(function() {
            $.ajax({
                url: "<?= _AJX_URI_ ?>cpanel.php",
                dataType: "json",
                data: {id: $(this).attr("data"), cpanel: $(this).attr("rel")},
                success: function(j) {
                    if (j == null)
                        window.location.reload();
                    else {
                        var elform, elinput;
                        var target = "_blank" + Math.floor((Math.random() * 100) + 1);
                        elform = $(document.createElement("form"))
                                .attr("action", "https://pagseguro.uol.com.br/security/webpagamentos/webpagto.aspx")
                                .attr("method", "post")
                                .attr("target", target);

                        elinput = $(document.createElement("input"))
                                .attr("type", "hidden")
                                .attr("name", "email_cobranca")
                                .val(j.email_pagseguro);
                        elform.append(elinput);

                        elinput = $(document.createElement("input"))
                                .attr("type", "hidden")
                                .attr("name", "tipo")
                                .val("CP");
                        elform.append(elinput);

                        elinput = $(document.createElement("input"))
                                .attr("type", "hidden")
                                .attr("name", "moeda")
                                .val("BRL");
                        elform.append(elinput);

                        elinput = $(document.createElement("input"))
                                .attr("type", "hidden")
                                .attr("name", "item_id_1")
                                .val(j.identity);
                        elform.append(elinput);

                        elinput = $(document.createElement("input"))
                                .attr("type", "hidden")
                                .attr("name", "item_descr_1")
                                .val(j.name);
                        elform.append(elinput);

                        elinput = $(document.createElement("input"))
                                .attr("type", "hidden")
                                .attr("name", "item_quant_1")
                                .val("1");
                        elform.append(elinput);

                        elinput = $(document.createElement("input"))
                                .attr("type", "hidden")
                                .attr("name", "item_valor_1")
                                .val(j.price);
                        elform.append(elinput);

                        elinput = $(document.createElement("input"))
                                .attr("type", "hidden")
                                .attr("name", "item_valorunit_1")
                                .val(j.price);
                        elform.append(elinput);

                        elinput = $(document.createElement("input"))
                                .attr("type", "hidden")
                                .attr("name", "item_peso_1")
                                .val("0");
                        elform.append(elinput);

                        window.open("", target, "height=570, width=990");

                        elform.submit();
                    }
                }
            });

        });
    }

    if ($('.content.product').length) {
        $(".picturesproduct").colorbox({rel: 'products'});
        $("input[name='phone']").bind({
            focus: function() {
                $(this).mask("(99) 9999-9999?9", {placeholder: " "});
            },
            focusout: function() {
                var number, mask;
                $(this).unmask();
                number = $(this).val().replace(/\D/g, "");
                if (number.length > 10)
                    mask = "(99) 99999-999?9";
                else
                    mask = "(99) 9999-9999?9";
                $(this).mask(mask, {placeholder: " "});
            }
        });
        $("form#proposal.product").submit(function() {
            if (!$(this).find(".empty").length) {
                var data = $(this).serialize();
                $.ajax({
                    type: "post",
                    url: "<?= _ACT_URI_ ?>proposal.php",
                    data: data,
                    success: function(msg) {
                        if (msg == 'OK') {
                            $("form#proposal")[0].reset();
                            alarm("success", "A proposta acabou de ser enviada.");
                        }
                        else if (msg == 'ERROR')
                            alarm("error", "Estamos com problemas técnicos, por favor tente novamente mais tarde.");
                        else
                            alarm("warning", msg);
                    }
                });
            }
            return false;
        });
    }

});
